package com.niiwoo.civet.user.service.local;

import com.alibaba.dubbo.rpc.RpcContext;
import com.niiwoo.civet.trade.service.refund.RepaymentDubboService;
import com.niiwoo.civet.user.dao.entity.UserCreditCardAuthInfo;
import com.niiwoo.civet.user.dao.mapper.UserCreditCardAuthInfoMapperExt;
import com.niiwoo.civet.user.service.UserYXCreditCardDubboService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;

import java.util.Date;

/**
 * @author zzl
 * @create 2018-03-07 16:52
 * @desc 用户信用卡信息授权本地处理类
 **/
@Slf4j
@Service
public class UserCreditCardAuthLocalService {

    @Autowired
    private UserCreditCardAuthInfoMapperExt userCreditCardAuthInfoMapperExt;

    @Autowired
    UserYXCreditCardDubboService userYXCreditCardDubboService;

    /**
     * 保存用户信用卡附加信息
     * @param userId
     * @param loginName
     * @param entryId
     * @param callbackTime
     */
    @Transactional
    public void saveUserCreditCardAuthInfo(String userId, String loginName, String entryId, Date callbackTime){

        //保存信用卡信息
        UserCreditCardAuthInfo userCreditCardAuthInfo = userCreditCardAuthInfoMapperExt.selectByPrimaryKey(userId);
        UserCreditCardAuthInfo record = new UserCreditCardAuthInfo();
        record.setCallbackTime(callbackTime);
        record.setEntryId(entryId);
        record.setLoginName(loginName);
        record.setUserId(userId);
        if(userCreditCardAuthInfo == null){
            userCreditCardAuthInfoMapperExt.insert(record);
        }else {
            userCreditCardAuthInfoMapperExt.updateByPrimaryKeySelective(record);
        }

        //查询天秤信用卡详细数据并保存
        TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
            @Override
            public void afterCommit() {
                super.afterCommit();
                RpcContext.getContext().asyncCall(new Runnable() {
                    @Override
                    public void run() {
                        userYXCreditCardDubboService.saveYXCreditCardData(userId);
                    }
                });
            }
        });

    }
}
